package com.lib.utils;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

/**
 * 不需要序列化的可以添加：@JSONField(serialize = false, deserialize = false)
 */
public class JSONUtils {
    public static String toJSONString(Object obj) {
        if (obj == null) {
            return "";
        }
        String str;
        try {
            str = JSON.toJSONString(obj);
        } catch (Throwable e) { //
            str = "";
        }
        return str;
    }

    public static JSONObject parseObject(String json) {
        JSONObject jsonObject = null;
        try {
            jsonObject = JSON.parseObject(json);
        } catch (Throwable e) {
            XLog.w("catch info\n" + Log.getStackTraceString(e), 6);
        }
        return jsonObject;
    }

    public static <T> T parseObject(String json, Class<T> tClass) {
        T object = null;
        try {
            object = JSON.parseObject(json, tClass);
        } catch (Throwable e) { //
            XLog.w("catch info->" + Log.getStackTraceString(e), 6);
        }
        return object;
    }

    public static <T> List<T> parseArray(String json, Class<T> tClass) {
        if (json == null || TextUtils.isEmpty(json = json.trim())) {
            return null;
        }
        List<T> object = null;
        try {
            object = JSON.parseArray(json, tClass);
        } catch (Throwable e) { //
        }
        return object;
    }
}